# coding=utf-8
import re
import codecs
import MySQLdb

"""QQ message analysis:
data struct:
    msglst = [
        [date1, time1, nickname1, qq1, msg1],
        [date2, time2, nickname2, qq2, msg2],
        [date3, time3, nickname3, qq3, msg3],
        [date4, time4, nickname4, qq4, msg4],
        [date5, time5, nickname5, qq5, msg5],
        ...
    ]

Regular Expression:
    date:       \d{4}-\d{2}-\d{2}
    time:       ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]
    nickname:   \w+
    qq:         \(\d{5, 11}\)
    msg:        \w+
"""


class Analysis(object):
    def __init__(self, **kwargs):
        msgbase = kwargs.get('msgbase', None)
        dbinfo = kwargs.get('dbinfo', None)
        self.msg = []

        if msgbase:
            self.__prase(msgbase)
        if dbinfo:
            # super(Analysis, self).__init__(**kwargs)
            self.hander(dbinfo)

    def hander(self, **dbinfo):
        """Use MySQL as the default database"""
        user = kwargs.get('user', 'root')
        password = kwargs.get('password', '')
        host = kwargs.get('host', '127.0.0.1')
        port = kwargs.get('port', '3306')
        db = kwargs.get('db', 'test')
        charset = kwargs.get('charset', 'utf8')
        conn = MySQLdb.connect(user=user,
                               passwd=password,
                               host=host,
                               charset=charset)
        try:
            conn.select_db(db)
        except:
            cursor.execute("CREATE DATABASE IF NOT EXISTS %s" % db)

        try:
            cursor.execute("""CREATE TABLE IF NOT EXISTS QQ(
                            id int(11) AUTO_INCREMENT,
                            qq varchar(255),
                            nickname varchar(255),
                            groupname varchar(255),
                            avatar_wrap varchar(255),
                            PRIMARY KEY (id)
                            )ENGINE=InnoDB DEFAULT CHARSET=utf8;
                           """)

            cursor.execute("""CREATE TABLE IF NOT EXISTS Messages(
                            id int(11) AUTO_INCREMENT,
                            time datetime,
                            qq varchar(255),
                            msg text,
                            PRIMARY KEY (id),
                            FOREIGN KEY (qq) REFERENCE QQ(id)
                            )ENGINE=InnoDB DEFAULT CHARSET=utf8;
                           """)

            conn.commit()
        except Exception, e:
            traceback.print_exec
            cursor.close()
            conn.close()
            return

        self.db_connect = conn

    def rank(self, length=5):
        cursor = self.db_connect.cursor()
        cursor.execute("""select count(*) from Messages
                        group by qq limit 0, %s""" % length)

    def get(self, uin=None, name=None):
        pass

    def save(self):
        cursor = self.conn.cursor()
        for q in self.qq:
            sql = """INSERT INTO QQ(qq, nickname, groupname, avatar_wrap) VALUES(
                  '%s', '%s', '%s', '%s')""" % (q[0], q[1], q[2], q[3])
            cursor.execute(sql)

        for m in self.msg:
            sql = """INSERT INTO QQ(time, nickname, groupname, avatar_wrap) VALUES(
                  '%s', '%s', '%s', '%s')""" % (m[0], m[1], m[2], m[3], m[4])
            cursor.execute(sql)

    def prase(self, msgbase):
        with codecs.open(msgbase, 'r', 'utf-8') as f:
            lines = f.readlines()
            # pattern = """(\d{4}-\d{2}-\d{2}) (([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]) (\w+) (\(\d{5, 11}\))"""
            pattern = """(\d{4}-\d{2}-\d{2}) (([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9])"""
            for line in lines:
                line = line.strip()
                lst = re.split(pattern, line, maxsplit=0)
                self.msg.append(lst)
                    
                continue
            f.close()


    def analysis(self, uin=None):
        pass
        
    __prase = prase

if __name__ == '__main__':
    msgbase = 'E:py.txt'
    m = Analysis(msgbase=msgbase)
    for i in m.msg:
        print i
    